package com.mright.common.shiro;


import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.mright.entity.SysPermission;
import com.mright.entity.SysRole;
import com.mright.entity.SysUser;
import com.mright.service.AccountService;



/**
 *  自定义认证授权配置
 */
public class MyShiroRealm extends AuthorizingRealm {

	@Resource
    private AccountService accountService;
	
	/*
	 * 登录信息和用户验证信息验证(non-Javadoc)
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		System.out.println("开始身份验证");
        String username = (String) token.getPrincipal(); //获取用户名，默认和login.html中的username对应。
	    if(null != username){
	    	 try {
				SysUser user =  accountService.findByUserName(username);
				if(null==user) return null;
				 String name = getName();
				 return new SimpleAuthenticationInfo(user,user.getPassWord(),name);
			} catch (Exception e) {
				throw new RuntimeException(e.getMessage());
			}
	     }else{
	    	 return null;
	     }
	}

	/*
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用,负责在应用程序中决定用户的访问控制的方法(non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("开始授权配置");
	    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
	    SysUser user  = (SysUser)principals.getPrimaryPrincipal();
	    List<SysRole> rolesInUser;
	    List<SysPermission> permissionsInUser;
		try {
			rolesInUser = accountService.getRolesByUserId(user.getId());
			permissionsInUser = accountService.getPermissionsByUserId(user.getId());
			for(SysRole role:rolesInUser){
		        authorizationInfo.addRole(role.getRoleName());
		    }
		    for(SysPermission p:permissionsInUser){
	            authorizationInfo.addStringPermission(p.getPermission());
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	    return authorizationInfo;
	}

}
